import VueRouter  from "vue-router";
import Vue from "vue";
Vue.use(VueRouter)

// 引入对应的页面组件
import Home from '@/views/Home'
import Category from '@/views/Category'
import Cart from '@/views/Cart'
import Topic from '@/views/Topic'
import User from '@/views/User'

const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', redirect: '/home' },
        { path: '/home', component: Home },
        { path: '/topic', component: Topic },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User },

    ]
})


//路由前置守卫
router.beforeEach((to,from,next)=>{
    next()
    //有token就表示已经登陆
    //想要进入购物车页面，必须有登录标识token
    let token = localStorage.getItem('token')
    if(to.path == '/cart'){
        //此时必须要有token
        if(token){
            next(); //next()去到to所对应的路由界面
        }else{
            Vue.prototype.$toast('请先登录')
            //定时器
            setTimeout(()=>{
                next("/user");
            },1000);
        }
    }else{
        //如果不是去往购物车的路由，则直接通过守卫，去到to所对应的路由界面
        next ( )
    }
})

export default router